// src/features/workspaces/components/create-workspace-modal.tsx
'use client';
import React, {useState} from 'react';
import {useCreateWorkspaceModal} from "@/features/workspaces/store/use-create-workspace-modal";
import {Dialog, DialogContent, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {useCreateWorkspace} from "@/features/workspaces/api/use-create-workspace";
import {useRouter} from "next/navigation";
import {toast} from "sonner";
import {useCurrentUser} from "@/hooks/use-current-user";

const CreateWorkspaceModal = () => {
    const router = useRouter()
    const user = useCurrentUser()

    const [open, setOpen] = useCreateWorkspaceModal();
    const [name, setName] = useState('')

    const {mutate, isPending} = useCreateWorkspace();

    const handleClose = () => {
        setOpen(false);
        // clear form
        setName('')
    }

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        if (!isPending) {
            const data = await mutate({name, userId: user?.id!}, {
                onSuccess(id) {
                    toast.success('Workspace created')
                    router.push(`/social/workspace/${id}`)
                    handleClose()
                    router.refresh()
                },
                onError() {
                },
                onSettled() {
                }
            })
        }
    }

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Add a workspace</DialogTitle>
                </DialogHeader>
                <form
                    onSubmit={handleSubmit}
                    className={`space-y-4`}>
                    <Input
                        value={name}
                        onChange={e => setName(e.target.value)}
                        disabled={isPending}
                        required
                        autoFocus
                        minLength={3}
                        placeholder={'Workspace name e.g. "Work", "Personal", "Home"'}
                    />
                    <div className={`flex justify-end`}>
                        <Button
                            type={'submit'}
                            disabled={isPending}>
                            Create
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
};

export default CreateWorkspaceModal;